import { async } from '@angular/core/testing';
import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STRequestOptions, STChange } from '@delon/abc/st';
import { SFComponent, SFSchema, SFDateWidgetSchema, SFAutoCompleteWidgetSchema, SFSelectWidgetSchema } from '@delon/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { AddCollectionInvoiceModalComponent } from 'src/app/routes/ticket-management/components/input-invoice/add-collection-invoice-modal/add-collection-invoice-modal.component';

import { PartnerListService } from '../../services/partner-list.service';
import { PartnerAuditModalComponent } from '../partner-audit-modal/partner-audit-modal.component';
import { catchError, debounceTime, map, switchMap } from 'rxjs/operators';
@Component({
  selector: 'app-partner-list',
  templateUrl: './partner-list.component.html',
  styleUrls: ['../../../../commom/less/box.less']
})
export class PartnerListComponent {
  @ViewChild('st', { static: true })
  st!: STComponent;
  @ViewChild('sf', { static: false })
  sf!: SFComponent;
  columns: STColumn[] = this.initST();
  searchSchema: SFSchema = this.initSF();
  _$expand = false;
  isLoading: boolean = false;
  @ViewChild('editTemplate', { static: true })
  editTemplate: any;
  templateId: any;
  templates: any[] = [];

  @ViewChild('editCannel', { static: true })
  editCannel: any;
  customers: any[] = [];
  cannels: any[] = [];
  selectedRows: any[] = [];
  cannelItem: any = { channelId: null, effectiveNode: 1, enterpriseIdList: [], remark: '' };
  searchChange$ = new BehaviorSubject('');
  selectItem: any = {};

  constructor(public service: PartnerListService, private nzModalService: NzModalService, private router: Router) {
    this.loadSelectOptions();
  }
  ngOnInit(): void {
  }
  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.sf) {
      let params = { ...this.sf?.value };
      if (params.createTime) {
        params.createTime = { start: this.sf?.value?.createTime?.[0], end: this.sf?.value?.createTime?.[1] };
      }
      Object.assign(requestOptions.body, params);
    }
    return requestOptions;
  };

  loadSelectOptions() {
    this.service.getRebateConfig({ stateLocked: 1 }).subscribe(res => {
      if (res) {
        console.log(res);

        this.customers = res;
      }
    });
  }

  auditPartner(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '审核',
      nzContent: PartnerAuditModalComponent,
      nzComponentParams: { info: { ...item, enterpriseName: item.enterpriseName || item.contactName }, sourcePage: '合伙人审核列表' },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load(1);
      }
    });
  }

  editTemplateAction(item: any) {
    this.selectItem = item;
    this.templateId = item.templateId || null;
    const modal = this.nzModalService.create({
      nzTitle: '修改返佣模板',
      nzContent: this.editTemplate,
      nzOnOk: () => {
        if (!this.templateId) {
          this.service.msgSrv.warning('请选择返佣模板');
          return false;
        }
        this.confirmEditTemplate();
        return false;
      }
    });
  }

  private confirmEditTemplate() {
    const modal = this.nzModalService.confirm({
      nzTitle: '确定要修改返佣模板吗？',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_update_partner_template, {
            id: this.selectItem.id,
            templateId: this.templateId
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('修改成功');
              this.st.load(1);
              this.nzModalService.closeAll();
            }
          });
        return false;
      }
    });
  }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        break;
    }
  }

  editCannelAction(item: any) {
    this.selectItem = item;
    this.cannelItem = { channelId: null, effectiveNode: 1, enterpriseIdList: [], remark: '' };
    this.selectedRows = [];
    // 校验合伙人是否可修改渠道销售 true:可以修改 false：不可以修改
    this.service.request(this.service.$api_check_partenr_change_channel, { id: item.id }).subscribe(res => {
      if (res) {
        this.selectItem = item;
        const modal = this.nzModalService.create({
          nzTitle: '修改渠道销售',
          nzWidth: 650,
          nzContent: this.editCannel,
          nzOnOk: () => {
            if (!this.cannelItem.channelId) {
              this.service.msgSrv.warning('请选择渠道销售');
              return false;
            }
            if (!this.cannelItem.remark) {
              this.service.msgSrv.warning('请填写备注');
              return false;
            }
            this.confirmEditCannel(item);
            return false;
          }
        });
      }
    });
  }

  confirmEditCannel(item: any) {
    const modal = this.nzModalService.confirm({
      nzTitle: '确定提交吗？',
      nzOnOk: () => {
        this.cannelItem.enterpriseIdList = this.selectedRows.map(row => row.enterpriseId);
        this.service
          .request(this.service.$api_update_partner_channel_by_id, {
            ...this.cannelItem,
            id: item.id
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('修改成功');
              this.nzModalService.closeAll();
              this.st.load(1);
            }
          });
      }
    });
  }

  /**
   * 重新发起crm
   * @param item
   */
  reSendCRM(item: any) {
    const modal = this.nzModalService.confirm({
      nzTitle: '是否确定重新发起CRM？',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_resend_crm, {
            id: item.id
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('发起成功');
            } else {
              this.service.msgSrv.warning('发起失败');
            }
            this.st.load(1);
          });
      }
    });
  }

  routeTo(route: string) {
    this.router.navigate([route]);
  }

  /**
   * 重置表单
   */
  resetSF() {
    this.sf.reset();
    this._$expand = false;
  }

  /**
   * 伸缩查询条件
   */
  expandToggle() {
    this._$expand = !this._$expand;
    this.sf?.setValue('/expand', this._$expand);
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        enterpriseName: {
          type: 'string',
          title: '合伙人名称'
        },
        contactMobile: {
          type: 'string',
          title: '手机号'
        },
        channelId: {
          type: 'string',
          title: '渠道销售',
          ui: {
            widget: 'select',
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => {
              let str = q.replace(/^\s+|\s+$/g, '');
              if (str) {
                return this.service.getChannel({ name: str }).toPromise();
              } else {
                return of([]);
              }
            }
          } as SFSelectWidgetSchema
        },
        partnerType: {
          type: 'string',
          title: '类型',
          enum: [
            { value: '', label: '全部' },
            { value: 1, label: '企业' },
            { value: 2, label: '个人' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        approvalStatus: {
          type: 'string',
          title: '认证审核状态',
          enum: [
            { value: '', label: '全部' },
            { value: '-1', label: '未提交' },
            { value: 10, label: '待审核' },
            { value: 20, label: '审核通过' },
            { value: 30, label: '认证驳回' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        signStatus: {
          type: 'string',
          title: '签约状态',
          enum: [
            { value: '', label: '全部' },
            { value: '0', label: '未签约' },
            { value: 10, label: '待合伙人签约' },
            { value: 15, label: '签约中' },
            { value: 20, label: '已签约' },
            { value: 30, label: '签约失败' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        crmStatus: {
          type: 'string',
          title: 'CRM状态',
          enum: [
            { value: '', label: '全部' },
            { value: '0', label: '未同步' },
            { value: 10, label: '同步失败' },
            { value: 20, label: '同步成功' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          }
        },
        paymo11de: {
          type: 'string',
          title: '注册渠道',
          enum: [
            { value: '', label: '全部' },
            { value: 1, label: '合伙人注册' },
            { value: 2, label: '平台添加' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        templateId: {
          type: 'string',
          title: '返佣模板',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            asyncData: () =>
              this.service.request(this.service.$api_get_rebate_config, {}, 'POST').pipe(
                map(data => {
                  if (data) {
                    return data.map((m: any) => {
                      return { label: m.configName, value: m.id };
                    });
                  } else {
                    return [];
                  }
                })
              ),
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        },
        lockedStatus: {
          type: 'string',
          title: '合伙人状态',
          enum: [
            { value: '', label: '全部' },
            { value: 0, label: '正常' },
            { value: 1, label: '冻结' }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择',
            visibleIf: {
              expand: (value: boolean) => value
            }
          },
          default: ''
        },
        createTime: {
          title: '注册时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            visibleIf: {
              expand: (value: boolean) => value
            }
          } as SFDateWidgetSchema
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      {
        title: '合伙人名称',
        render: 'enterpriseName',
        width: 180
      },
      { title: '付款编码', index: 'payCode', width: 160 },
      { title: '邀请码', index: 'invitationCode', className: 'text-center', width: 130 },
      { title: '手机号', index: 'contactMobile', className: 'text-center', width: 150 },
      { title: '类型', index: 'partnerType', className: 'text-center', width: 130, type: 'enum', enum: { 1: '企业', 2: '个人' } },
      { title: '注册渠道', index: 'source', type: 'enum', enum: { 1: '合伙人注册', 2: '平台添加' }, width: 130 },
      { title: '注册时间', index: 'createTime', className: 'text-center', width: 170 },
      { title: '渠道销售', index: 'channelIdLabel', width: 170 },
      { title: '返佣模板', index: 'templateName', width: 150 },
      {
        title: '认证审核状态',
        index: 'approvalStatus',
        width: 150,
        type: 'badge',
        badge: {
          '-1': { text: '未提交', color: 'default' },
          10: { text: '待审核', color: 'processing' },
          20: { text: '审核通过', color: 'success' },
          30: { text: '驳回', color: 'error' }
        }
      },
      {
        title: '签约状态',
        index: 'signStatus',
        width: 150,
        type: 'badge',
        badge: {
          0: { text: '未签约', color: 'default' },
          10: { text: '待合伙人签约', color: 'default' },
          15: { text: '签约中', color: 'processing' },
          20: { text: '已签约', color: 'success' },
          30: { text: '签约失败', color: 'error' }
        }
      },
      {
        title: 'CRM状态',
        index: 'crmStatus',
        width: 150,
        type: 'badge',
        badge: {
          0: { text: '未同步', color: 'default' },
          10: { text: '同步失败', color: 'error' },
          20: { text: '同步成功', color: 'success' }
        }
      },
      {
        title: '合伙人状态',
        index: 'lockedStatus',
        className: 'text-center',
        width: 140,
        type: 'badge',
        badge: {
          0: { text: '正常', color: 'success' },
          1: { text: '冻结', color: 'error' }
        }
      },
      {
        title: '操作',
        fixed: 'right',
        width: '150px',
        buttons: [
          { type: 'divider' },
          {
            text: '审核',
            acl: { ability: ['ENTERPRISE-audit'] },
            iif: item => item.id && item.approvalStatus === 10,
            click: item => this.auditPartner(item)
          },
          {
            text: '详情<br>',
            iif: item => item.id,
            acl: { ability: ['ENTERPRISE-detail'] },
            click: item => {
              if (item.partnerType === 1) {
                this.router.navigate([`/partner/partner-list/etp-detail/${item.id}`]);
              } else {
                this.router.navigate([`/partner/partner-list/personal-detail/${item.id}`]);
              }
            }
          },
          {
            text: '修改返佣模板',
            iif: item => item.id,
            acl: { ability: ['ENTERPRISE-updateTemplate'] },
            click: item => this.editTemplateAction(item)
          },
          {
            text: '修改渠道销售',
            iif: item => item.id,
            acl: { ability: ['ENTERPRISE-updateChannelCheck'] },
            click: item => this.editCannelAction(item)
          },
          {
            text: '重发CRM流程',
            acl: { ability: ['ENTERPRISE-reSendCrm'] },
            click: item => item.id && this.reSendCRM(item),
            iif: item => item.crmStatus === 10
          }
        ]
      }
    ];
  }
  onSearch(value: string): void {
    this.isLoading = true;
    let params: any = {};
    if (value) {
      console.log(+value);
      // 数字
      if (+value) {
        params.phoneNumber = value;
      } else {
        // 中文
        params.name = value;
      }
      this.service.request(this.service.$api_get_channel, params).subscribe(res => {
        let NewList: { label: string; value: any; }[] = [];
        let List = res.filter((i: any) => {
          NewList.push({ label: `${i.name}/${i.telephone}`, value: i.id }) ;
        });
        this.cannels = NewList
      });
      this.searchChange$.next(value);
    } else if(value === '') {
      this.service.request(this.service.$api_get_channel, {name: '清空数X'}).subscribe(res => {
        let NewList: { label: string; value: any; }[] = [];
        let List = res.filter((i: any) => {
          NewList.push({ label: `${i.name}/${i.telephone}`, value: i.id }) ;
        });
        this.cannels = NewList
      });
    }
  }
}
